﻿using ContactSMS.Commons.QueryParameters;
using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.Domain.PagedResult;
using ContactSMS.Infrastructure.dbContexts;
using Microsoft.EntityFrameworkCore;

namespace ContactSMS.Infrastructure
{
    public class MessageRepository : IMessageRepository
    {
        private readonly ContactDbContexts _contactDbContexts;

        public MessageRepository(ContactDbContexts contactDbContexts)
        {
            this._contactDbContexts = contactDbContexts;
        }

        public async Task<Message?> AddMessageAsync(Message message)
        {
            await _contactDbContexts.Messages.AddAsync(message);
            await _contactDbContexts.SaveChangesAsync();
            return message;
        }

        public async Task<List<Message>?> GetMessageByContactIdAsync(long contactId)
        {
            var result = await _contactDbContexts.Messages.Where(o => o.ContactId == contactId).ToListAsync();
            return result;
        }

        public async Task<bool> DeleteMessageByContactIdAsync(long ContactId)
        {
            var result = await GetMessageByContactIdAsync(ContactId);
            if (result != null)
            {
                _contactDbContexts.Messages.RemoveRange(result);
                await _contactDbContexts.SaveChangesAsync();
                return true;
            }
            return false;
        }

        public async Task<bool> DeleteMessageByContactIdsAsync(long[] contactId)
        {
            var messagesToDelete = await _contactDbContexts.Messages
                            .Where(message => contactId.Any(cid => cid == message.ContactId))
                            .ToListAsync();

            _contactDbContexts.Messages.RemoveRange(messagesToDelete);
            await _contactDbContexts.SaveChangesAsync();

            return messagesToDelete.Any();
        }

        public async Task<List<Message>?> GetMessageByMessageSessionIdAsync(long MessageSessionId)
        {
            var result = await _contactDbContexts.Messages.Where(o => o.MessageSessionId == MessageSessionId).ToListAsync();
            return result;
        }

        public async Task<bool> DeleteMessageByMessageSessionIdAsync(long MessageSessionId)
        {
            var result = await GetMessageByMessageSessionIdAsync(MessageSessionId);
            if (result != null)
            {
                _contactDbContexts.Messages.RemoveRange(result);
                await _contactDbContexts.SaveChangesAsync();
                return true;
            }
            return false;
        }

        public async Task<bool> DeleteMessageByMessageSessionIdsAsync(long[] MessageSessionId)
        {
            var messagesToDelete = await _contactDbContexts.Messages
                            .Where(message => MessageSessionId.Any(cid => cid == message.MessageSessionId))
                            .ToListAsync();

            _contactDbContexts.Messages.RemoveRange(messagesToDelete);
            await _contactDbContexts.SaveChangesAsync();

            return messagesToDelete.Any();
        }

        public async Task<bool> DeleteMessageByIdAsync(long id)
        {
            var existing = await _contactDbContexts.Messages.FirstOrDefaultAsync(x => x.Id == id);
            if (existing == null)
            {
                return false;
            }
            _contactDbContexts.Messages.Remove(existing);
            await _contactDbContexts.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteMessageByIdsAsync(long[] ids)
        {
            var list = await _contactDbContexts.Messages.Where(Messages => ids.Contains(Messages.Id)).ToListAsync();
            if (!list.Any())
            {
                return false;
            }
            _contactDbContexts.Messages.RemoveRange(list);
            await _contactDbContexts.SaveChangesAsync();
            return true;
        }

        public Task<bool> DeleteMessageByMobileAsync(string mobile)
        {
            throw new NotImplementedException();
        }

        public async Task<PagedMessageResult> GetMessageAsync(MessageQueryParameters parameters, int page = 1, int pageSize = 10, long MessageSessionId = 0)
        {
            var query = _contactDbContexts.Messages.AsQueryable();
            query = query.Where(c => c.MessageSessionId.Equals(MessageSessionId));
            // 筛选条件
            if (!string.IsNullOrEmpty(parameters.SearchTerm))
            {
                query = query.Where(c => c.Desc.Contains(parameters.SearchTerm));
            }
            // 排序方式
            if (!string.IsNullOrEmpty(parameters.SortBy))
            {
                query = ApplySorting(query, parameters.SortBy, parameters.SortDescending);
            }
            // 获取总记录数
            var totalCount = await query.CountAsync();
            // 计算总页数
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            // 分页查询
            var result = await query
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
            return new PagedMessageResult
            {
                Message = result,
                CurrentPage = page,
                TotalPages = totalPages,
            };
        }

        private IQueryable<Message> ApplySorting(IQueryable<Message> query, string sortBy, bool sortDescending)
        {
            // 根据排序字段和排序方向对查询进行排序
            switch (sortBy.ToLower())
            {
                case "creattime":
                    query = sortDescending ? query.OrderByDescending(c => c.CreatTime) : query.OrderBy(c => c.CreatTime);
                    break;
                // 可以根据需要添加更多的排序字段
                default:
                    // 默认按照 ID 排序
                    query = sortDescending ? query.OrderByDescending(c => c.Id) : query.OrderBy(c => c.Id);
                    break;
            }
            return query;
        }
    }
}
